package com.util;

import cn.hutool.core.io.FileUtil;
import com.domain.LocalFile;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class VideoUtil {

    private static final String ROOT_PATH = System.getProperty("user.dir") + "\\file\\";

    /**
     * 获取指定视频的帧并保存为图片
     *
     * @param file      源视频文件地址
     * @param frameFile 截取帧的图片存放地址
     * @throws Exception
     */
    public static LocalFile fetchCover(File file, String frameFile) throws Exception {
        // 启动录制器
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
        ff.start();
        int length = ff.getLengthInFrames();
        int i = 0;
        Frame frame = null;
        while (i < length) {
            // 过滤前5帧，避免出现全黑的图片，依自己情况而定
            frame = ff.grabFrame();
            if ((i > 5) && (frame.image != null)) {
                break;
            }
            i++;
        }

        // 对截取的帧进行等比例缩放
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage srcBi = converter.getBufferedImage(frame);
        int oWidth = srcBi.getWidth();
        int oHeight = srcBi.getHeight();
        int width = 800;
        int height = (int) (((double) width / oWidth) * oHeight);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        bi.getGraphics().drawImage(srcBi.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        ff.close();
        ff.stop();

        // 在本地生成图片
        String filePath = "videoCover" + File.separator + frameFile + ".jpg";
        File targetFile = new File(ROOT_PATH + filePath);
        try {
            ImageIO.write(bi, "jpg", targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 返回图片信息，让后台存入数据库
        LocalFile fileCover = new LocalFile();
        fileCover.setFileName(FileUtil.mainName(targetFile));
        fileCover.setFileType("videoCover");
        fileCover.setFileSuffix(FileUtil.getType(targetFile));
        fileCover.setFilePath(filePath);
        fileCover.setFileMd5(FileUtilLocal.getFileMD5(targetFile));
        return fileCover;
    }

    /**
     * 获取视频时长，单位为秒
     *
     * @param file 即为视频地址
     * @return 时长（秒）
     */
    public static Integer getVideoTime(File file) {
        Long times = 0L;
        try {
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
            ff.start();
            times = ff.getLengthInTime() / (1000 * 1000);
            ff.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Math.toIntExact(times);
    }

}